package javatunes;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.TreeSet;

import javazoom.jl.player.Player;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Shell;

import player.PlayerControl;
import player.PlayerFactory;

import com.cloudgarden.resource.SWTResourceManager;


/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
public class javatunes2 extends org.eclipse.swt.widgets.Composite {

	int currentplayer=0;
	final int CURRENT_IBM=0;
	final int CURRENT_JLAYER=1; 
	
	
	TreeSet<String> artists;
	TreeSet<String> albums;
	// TreeSet<String> titles;
	TreeSet<String> genres;
	String[] artists_arr;
	String[] albums_arr;
	mhit[] track_arr;
	private Button previousbutton;
	private Button showremotebutton;
	private Button nextbutton;
	private Button pausebutton;
	private Button stopbutton;
	private Composite composite1;
	String[] genres_arr;
	
	Shell remotecontrol=null;
	
	ArrayList<mhit> tracks;
	
	private static javatunes2 jt2;
	public static itunesdbreader itunesdb;
	
	Menu menu1;
	MenuItem exitMenuItem;
	Button exportbutton;
	Button playbutton;
	List titlelist;
	List albumlist;
	List artistlist;
	List genrelist;
	Menu fileMenu;
	MenuItem fileMenuItem;
	
	int currenttrack=0;
	
	PlayerControl ibmPlayer;
	Player jlayerPlayer;
	
	{
		//Register as a resource user - SWTResourceManager will
		//handle the obtaining and disposing of resources
		SWTResourceManager.registerResourceUser(this);
	}

	public javatunes2(Composite parent, int style, ArrayList<mhit> alltracks) {
		super(parent, style);
		this.tracks=alltracks;
		setuparraylists(tracks);
		ibmPlayer=PlayerFactory.createLightweightMPEG4Player();
		ibmPlayer.addListener(new javatunesplayerlistener(this));
		ibmPlayer.setPlayerEndAction(PlayerControl.END_ACTION_STOP);
		initGUI();
		remotecontrol=javatunes2remote.initRemote(this);
	}
	
	public void setuparraylists(ArrayList<mhit> tracks) {
		artists=new TreeSet<String>();
		albums=new TreeSet<String>();
		//titles=new TreeSet<String>();
		genres=new TreeSet<String>();
		
		genres.add("(All)");
		artists.add("(All)");
		albums.add("(All)");
		//titles.add("(All)");
		
		mhit current;
		for (int i=0; i<tracks.size(); i++) {
			current=tracks.get(i);
			if (current.artist.length()>0) artists.add(current.artist);
			if (current.album.length()>0) albums.add(current.album);
			//if (current.title.length()>0) titles.add(current.title);
			if (current.genre.length()>0) genres.add(current.genre);
		}

		artists_arr=artists.toArray(new String[0]);
		albums_arr=albums.toArray(new String[0]);
		track_arr=tracks.toArray(new mhit[0]);
		Arrays.sort(track_arr);
		genres_arr=genres.toArray(new String[0]);
	}
	
	void updateartistlist() {
		artistlist.setItems(artists_arr);
	}
	
	void updatealbumlist() {
		albumlist.setItems(albums_arr);
		
	}
	
	void updatetitlelist() {
		titlelist.removeAll();
		for (mhit track:track_arr) titlelist.add(track.toString());
	}
	
	/**
	* Initializes the GUI.
	*/
	private void initGUI() {
		try {
			this.setSize(1000, 600);
			this.setBackground(SWTResourceManager.getColor(192, 192, 192));
			GridLayout thisLayout = new GridLayout();
			thisLayout.makeColumnsEqualWidth = true;
			thisLayout.numColumns = 3;
			this.setLayout(thisLayout);
			{
				GridData list1LData = new GridData();
				list1LData.horizontalAlignment = GridData.FILL;
				list1LData.verticalAlignment = GridData.BEGINNING;
				genrelist = new List(this, SWT.MULTI | SWT.V_SCROLL);
				genrelist.setLayoutData(list1LData);
				genrelist.setItems(genres_arr);
				genrelist.setSize(166, 200);
				genrelist.addSelectionListener(new SelectionAdapter() {
					public void widgetSelected(SelectionEvent evt) {
						genrelistWidgetSelected(evt);
					}
				});
			}
			{
				GridData list2LData = new GridData();
				list2LData.horizontalAlignment = GridData.FILL;
				list2LData.verticalAlignment = GridData.BEGINNING;
				list2LData.heightHint = 200;
				artistlist = new List(this, SWT.MULTI | SWT.V_SCROLL);
				artistlist.setLayoutData(list2LData);
				artistlist.setItems(artists_arr);
				artistlist.setSize(166, 200);
				artistlist.addSelectionListener(new SelectionAdapter() {
					public void widgetSelected(SelectionEvent evt) {
						artistlistWidgetSelected(evt);
					}
				});
			}
			{
				GridData list3LData = new GridData();
				list3LData.horizontalAlignment = GridData.FILL;
				list3LData.verticalAlignment = GridData.BEGINNING;
				list3LData.heightHint = 200;
				albumlist = new List(this, SWT.MULTI | SWT.V_SCROLL);
				albumlist.setLayoutData(list3LData);
				albumlist.setItems(albums_arr);
				albumlist.setSize(166, 200);
				albumlist.addSelectionListener(new SelectionAdapter() {
					public void widgetSelected(SelectionEvent evt) {
						albumlistWidgetSelected(evt);
					}
				});
			}
			{
				GridData list4LData = new GridData();
				list4LData.horizontalSpan = 3;
				list4LData.horizontalAlignment = GridData.FILL;
				list4LData.verticalAlignment = GridData.FILL;
				list4LData.grabExcessVerticalSpace = true;
				list4LData.grabExcessHorizontalSpace = true;
				titlelist = new List(this, SWT.SINGLE | SWT.V_SCROLL);
				titlelist.setLayoutData(list4LData);
				updatetitlelist();
			}
			{
				composite1 = new Composite(this, SWT.NONE);
				GridLayout composite1Layout = new GridLayout();
				composite1Layout.makeColumnsEqualWidth = true;
				composite1Layout.numColumns = 5;
				GridData composite1LData = new GridData();
				composite1LData.horizontalAlignment = GridData.CENTER;
				composite1.setLayoutData(composite1LData);
				composite1.setLayout(composite1Layout);
				{
					playbutton = new Button(composite1, SWT.PUSH | SWT.CENTER);
					GridData button2LData = new GridData();
					playbutton.setLayoutData(button2LData);
					playbutton.setText("Play");
					playbutton.addSelectionListener(new SelectionAdapter() {
						public void widgetSelected(SelectionEvent evt) {
							playbuttonWidgetSelected(evt);
						}
					});
				}
				{
					pausebutton = new Button(composite1, SWT.PUSH | SWT.CENTER);
					GridData pausebuttonLData = new GridData();
					pausebuttonLData.horizontalAlignment = GridData.CENTER;
					pausebutton.setLayoutData(pausebuttonLData);
					pausebutton.setText("Pause");
					pausebutton.addSelectionListener(new SelectionAdapter() {
						public void widgetSelected(SelectionEvent evt) {
							pausebuttonWidgetSelected(evt);
						}
					});
				}
				{
					stopbutton = new Button(composite1, SWT.PUSH | SWT.CENTER);
					GridData stopbuttonLData = new GridData();
					stopbuttonLData.horizontalAlignment = GridData.CENTER;
					stopbutton.setLayoutData(stopbuttonLData);
					stopbutton.setText("Stop");
					stopbutton.addSelectionListener(new SelectionAdapter() {
						public void widgetSelected(SelectionEvent evt) {
							stopbuttonWidgetSelected(evt);
						}
					});
				}
				{
					previousbutton = new Button(composite1, SWT.PUSH
						| SWT.CENTER);
					previousbutton.setText("<< Prev");
					previousbutton.addSelectionListener(new SelectionAdapter() {
						public void widgetSelected(SelectionEvent evt) {
							previousbuttonWidgetSelected(evt);
						}
					});
				}
				{
					nextbutton = new Button(composite1, SWT.PUSH | SWT.CENTER);
					nextbutton.setText("Next >>");
					nextbutton.addSelectionListener(new SelectionAdapter() {
						public void widgetSelected(SelectionEvent evt) {
							nextbuttonWidgetSelected(evt);
						}
					});
				}
			}
			{
				showremotebutton = new Button(this, SWT.PUSH | SWT.CENTER);
				GridData showremotebuttonLData = new GridData();
				showremotebuttonLData.horizontalAlignment = GridData.CENTER;
				showremotebutton.setLayoutData(showremotebuttonLData);
				showremotebutton.setText("Show Remote");
				showremotebutton.addSelectionListener(new SelectionAdapter() {
					public void widgetSelected(SelectionEvent evt) {
						showremotebuttonWidgetSelected(evt);
					}
				});
			}
			{
				exportbutton = new Button(this, SWT.PUSH | SWT.CENTER);
				GridData button1LData = new GridData();
				button1LData.horizontalAlignment = GridData.CENTER;
				exportbutton.setLayoutData(button1LData);
				exportbutton.setText("Export playlist");
				exportbutton.addSelectionListener(new SelectionAdapter() {
					public void widgetSelected(SelectionEvent evt) {
						exportbuttonWidgetSelected(evt);
					}
				});
			}
			{
				menu1 = new Menu(getShell(), SWT.BAR);
				getShell().setMenuBar(menu1);
				{
					fileMenuItem = new MenuItem(menu1, SWT.CASCADE);
					fileMenuItem.setText("File");
					{
						fileMenu = new Menu(fileMenuItem);
						{
							exitMenuItem = new MenuItem(fileMenu, SWT.CASCADE);
							exitMenuItem.setText("Exit");
							exitMenuItem
								.addSelectionListener(new SelectionAdapter() {
								public void widgetSelected(SelectionEvent evt) {
									exitMenuItemWidgetSelected(evt);
								}
								});

						}
						fileMenuItem.setMenu(fileMenu);
					}
				}
			}
			{
				getShell().addShellListener(new ShellAdapter() {
					public void shellClosed(ShellEvent evt) {
						activeShellShellClosed(evt);
					}
				});
			}
			this.layout();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	* Auto-generated main method to display this 
	* org.eclipse.swt.widgets.Composite inside a new Shell.
	*/
	public static void main(String[] args) throws Exception {
		System.out.println("initialising itunesdbreader...");
		itunesdb=new itunesdbreader();
		
		Display display = Display.getDefault();
		Shell shell = new Shell(display, SWT.ON_TOP);
		javatunes2 inst = new javatunes2(shell, SWT.NULL,itunesdb.alltracks);
		Point size = inst.getSize();
		shell.setLayout(new FillLayout());
		shell.setText("javatunes2");
		shell.layout();
		if(size.x == 0 && size.y == 0) {
			inst.pack();
			shell.pack();
		} else {
			Rectangle shellBounds = shell.computeTrim(0, 0, size.x, size.y);
			shell.setSize(shellBounds.width, shellBounds.height);
		}
		shell.open();
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch())
				display.sleep();
		}
	}
	
	private void exportbuttonWidgetSelected(SelectionEvent evt) {
		String[] filterExtensions = {"*.pls"};
		FileDialog fileDialog = new FileDialog(getShell(), SWT.SAVE);
		fileDialog.setText("Choose playlist export");
		fileDialog.setFilterPath("C:/");
		fileDialog.setFilterExtensions(filterExtensions);
		String selectedFile = fileDialog.open();
		System.out.println("selectedFile: "+selectedFile);
		if (selectedFile!=null) {
			File file=new File(selectedFile);
			try {
		        FileOutputStream fout = new FileOutputStream(file);
		        PrintStream out=new PrintStream(fout);
		        out.println("[playlist]");
		        for (int i=0;i<track_arr.length;i++) {
					out.println("File"+(i+1)+"="+track_arr[i].getFileName(itunesdbreader.IPODDRIVE));	
				}
		        out.close();
		        fout.close();
		    } catch (IOException e) {
		    	e.printStackTrace();
		    }
		    System.out.println("");
		}
	}
	
	private void genrelistWidgetSelected(SelectionEvent evt) {
		tracks=itunesdbreader.search(itunesdb.alltracks,null,null,null,genrelist.getSelection());
		setuparraylists(tracks);
		updateartistlist();
		updatealbumlist();
		updatetitlelist();
	}
	
	private void artistlistWidgetSelected(SelectionEvent evt) {
		tracks=itunesdbreader.search(itunesdb.alltracks,artistlist.getSelection(),null,null,genrelist.getSelection());
		setuparraylists(tracks);
		updatealbumlist();
		updatetitlelist();
	}
	
	private void albumlistWidgetSelected(SelectionEvent evt) {
		tracks=itunesdbreader.search(itunesdb.alltracks,artistlist.getSelection(),albumlist.getSelection(),null,genrelist.getSelection());
		setuparraylists(tracks);
		updatetitlelist();
	}
	
	private void playbuttonWidgetSelected(SelectionEvent evt) {
		play(false);
	}
		
	private void previousbuttonWidgetSelected(SelectionEvent evt) {
		previoustrack();
	}
	
	private void nextbuttonWidgetSelected(SelectionEvent evt) {
		nexttrack();
	}
	
	private void stopbuttonWidgetSelected(SelectionEvent evt) {
		stop();
	}
	
	private void pausebuttonWidgetSelected(SelectionEvent evt) {
		pause();
	}
	
	public void pause() {
		if (currentplayer==CURRENT_IBM) {
			if (ibmPlayer.canPause()) {
				try {
					int state=ibmPlayer.getState();
					switch (state) {
					case PlayerControl.PLAYING: ibmPlayer.pause();
					break;
					case PlayerControl.PAUSED: ibmPlayer.resume();
					break;
					}
				}
				catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		else {
			//jlayerPlayer.close();
		}
	}
	
	public void stop() {
		ibmPlayer.stopUrl();
		jlayerPlayer.close();
	}
		
	public void play(boolean currenttrackset) {
		if (!currenttrackset) {
			int[] selection=titlelist.getSelectionIndices();
			if (selection.length==0) {
				titlelist.setSelection(0);
				selection=titlelist.getSelectionIndices();
			}
			currenttrack=selection[0];
		}
		if (ibmPlayer.getState()==PlayerControl.PAUSED) {
			try { ibmPlayer.resume(); }
			catch (Exception e) {e.printStackTrace();}
			return;
		}
		mhit tracktoplay=track_arr[currenttrack];
		ibmPlayer.stopUrl();
		String filename=tracktoplay.getFileName(itunesdbreader.IPODDRIVE);
		if (tracktoplay.getExtension().equals("mp3")) {
			currentplayer=CURRENT_JLAYER;
			System.out.println("mp3...");
			try {
				jlayerPlayer=new Player(new FileInputStream(new File(filename)));
				new Thread() {
					public void run() {
						try {
							jlayerPlayer.play();
						}
						catch (Exception e) {
							e.printStackTrace();
						}
					}
				}.start();
			}
			catch (Exception e) {
				e.printStackTrace();
			}
		}
		else {
			currentplayer=CURRENT_IBM;
			System.out.println(tracktoplay.getExtension());
			ibmPlayer.playUrl(filename);
		}
	}
	
	public void nexttrack() {
		currenttrack++;
		if (currenttrack<0) currenttrack=0;
		if (currenttrack>=track_arr.length) currenttrack=0;
		updateselection(currenttrack);
		play(true);
	}
	
	public void previoustrack() {
		currenttrack--;
		if (currenttrack<0) currenttrack=track_arr.length-1;
		if (currenttrack>=track_arr.length) currenttrack=track_arr.length-1;
		updateselection(currenttrack);
		play(true);
	}
	
	private void updateselection(final int selection) {
		getDisplay().syncExec(new Runnable () {
			public void run() { 
				titlelist.select(selection);
			}
		});
	}
	
	private void shutdown() {
		ibmPlayer.stopUrl();
		System.exit(0);
	}
	
	private void exitMenuItemWidgetSelected(SelectionEvent evt) {
		shutdown();
	}
	
	private void activeShellShellClosed(ShellEvent evt) {
		
		shutdown();
	}
	
	private void showremotebuttonWidgetSelected(SelectionEvent evt) {
		if (remotecontrol.isVisible()) remotecontrol.setVisible(false);
		else {
			remotecontrol.setActive();
			remotecontrol.setVisible(true);
			remotecontrol.setLocation(500,0);
		}
	}
}
